<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小同住人员物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\housing;

use think\App;
use app\controller\property\Base;
use think\exception\ValidateException;
use app\validate\housing\HousingResourceValidate;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\housing\HousingLogRepository;
use app\common\repositories\housing\HousingLabelRepository;
use app\common\repositories\housing\HousingResourceRepository;
use app\common\repositories\property\basic\PropertyCateRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;
use app\common\repositories\property\basic\PropertyFacilityRepository;


class HousingResource extends Base
{
    protected $repository;

    public function __construct(App $app, HousingResourceRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyHousingResourceAdd'),
            'editAuth' => property_auth('propertyHousingResourceEdit'),
            'delAuth' => property_auth('propertyHousingResourceDel'),
            'detailAuth' => property_auth('propertyHousingResourceDetail'),
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        return $this->fetch('housing/resource/list');
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'source_id' => '',
                'housing_title' => '',
                'rent_price' => '',
                'rent_type' => '',
                'room_size' => '',
                'floor_name' => '',
                'floor_total' => '',
                'pay_num' => '',
                'bet_num' => '',
                'start_rent' => '',
                'cate_id' => '',
                'is_reg' => '',
                'free_rent' => '',
                'address' => '',
                'label_id' => '',
                'picture' => '',
                'longitude' => '',
                'latitude' => '',
                'facilit' => '',
                'remark' => '',
            ]);
            validate(HousingResourceValidate::class)->scene('add')->check($param);
            $param['source_type'] = 'basic';
            $facilit = [];
            if (isset($param['facilit']) && is_array($param['facilit'])) {
                foreach ($param['facilit'] as $k => $v) {
                    if (isset($v['selected']) && isset($v['num']) && $v['num'] > 0) {
                        $facilit[] = [
                            'id' => $k,
                            'num' => (int)$v['num']
                        ];
                    }
                }
            }
            $param['facilit'] = $facilit;
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加房源失败', $e);
                return $this->error('网络失败');
            }
        } else {

            /** @var HousingLabelRepository $housingLabelRepository */
            $housingLabelRepository = app()->make(HousingLabelRepository::class);
            $labelData = $housingLabelRepository->getLabelData($this->request->propertyId, ['is_show' => 1]);

            /** @var PropertyCateRepository $propertyCateRepository */
            $propertyCateRepository = app()->make(PropertyCateRepository::class);
            $cateData = $propertyCateRepository->getCateData($this->request->propertyId, ['is_show' => 1]);

            /** @var PropertyFacilityRepository $propertyFacilityRepository */
            $propertyFacilityRepository = app()->make(PropertyFacilityRepository::class);
            $facilitData = $propertyFacilityRepository->getFacilityData($this->request->propertyId, 1);
            $facilitData = array_chunk($facilitData->toArray(), count($facilitData) > 2 ? 2 : 1);

            /** @var RoomBasicRepository $roomBasicRepository */
            $roomBasicRepository = app()->make(RoomBasicRepository::class);
            $roomData = $roomBasicRepository->getSearch([])
                ->where('status', 1)
                ->where('property_id', $this->request->propertyId)
                ->append(['unit_room_name'])
                ->select()->toArray();

            return $this->fetch('housing/resource/add', [
                'cateData' => $cateData,
                'roomData' => $roomData,
                'labelData' => $labelData,
                'facilitData' => $facilitData,
            ]);
        }

    }

    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'housing_title' => '',
                'rent_price' => '',
                'rent_type' => '',
                'room_size' => '',
                'floor_name' => '',
                'floor_total' => '',
                'pay_num' => '',
                'bet_num' => '',
                'start_rent' => '',
                'cate_id' => '',
                'is_reg' => '',
                'free_rent' => '',
                'address' => '',
                'label_id' => '',
                'picture' => '',
                'longitude' => '',
                'latitude' => '',
                'facilit' => '',
                'remark' => '',
            ]);
            validate(HousingResourceValidate::class)->scene('edit')->check($param);
            $facilit = [];
            if (isset($param['facilit']) && is_array($param['facilit'])) {
                foreach ($param['facilit'] as $k => $v) {
                    if (isset($v['selected']) && isset($v['num']) && $v['num'] > 0) {
                        $facilit[] = [
                            'id' => $k,
                            'num' => (int)$v['num']
                        ];
                    }
                }
            }
            $param['facilit'] = $facilit;
            try {
                $param['label_id'] = str_replace(['[', ']'], '', $param['label_id']);
                $param['label_id'] = array_filter(explode(',', $param['label_id']));
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('修改房源失败', $e);
                return $this->error('网络错误');
            }
        } else {
            /** @var PropertyCateRepository $propertyCateRepository */
            $propertyCateRepository = app()->make(PropertyCateRepository::class);
            $cateData = $propertyCateRepository->getCateData($this->request->propertyId, ['is_show' => 1]);

            /** @var HousingLabelRepository $housingLabelRepository */
            $housingLabelRepository = app()->make(HousingLabelRepository::class);
            $labelData = $housingLabelRepository->getLabelData($this->request->propertyId, ['is_show' => 1]);

            /** @var PropertyFacilityRepository $propertyFacilityRepository */
            $propertyFacilityRepository = app()->make(PropertyFacilityRepository::class);
            $facilitData = $propertyFacilityRepository->getFacilityData($this->request->propertyId, 1);
            $facilitData = array_chunk($facilitData->toArray(), count($facilitData) > 2 ? 2 : 1);

            $housingFacility = convert_arr_key($info['facility'], 'facility_id');
            return $this->fetch('housing/resource/edit', [
                'info' => $info,
                'cateData' => $cateData,
                'labelData' => $labelData,
                'facilitData' => $facilitData,
                'housingFacility' => $housingFacility,
            ]);
        }
    }

    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除房源失败', $e);
            return $this->error('网络失败');
        }
    }

    public function detail()
    {
        $housingId = (int)$this->request->param('housing_id');
        if ($housingId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($housingId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('housing/resource/detail', [
            'info' => $info
        ]);
    }

    /**
     *  房源日志
     * @param HousingLogRepository $logRepository
     * @return \think\response\Json|void
     *
     * @author Amos
     * 2024-06-05 17:05
     */
    public function resourceLog(HousingLogRepository $logRepository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'housing_id' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $logRepository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }


}